package br.com.advance.automacao.web.administrativo;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.primefaces.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;

import br.com.advance.automacao.enumeration.Fabricante;
import br.com.advance.automacao.model.CLP;
import br.com.advance.automacao.services.CLPService;
import br.com.advance.automacao.services.exceptions.ValidationException;
import br.com.advance.automacao.web.utils.BaseBean;

@ManagedBean
@ViewScoped
public class EditarEquipamentoMBean extends BaseBean {

	/**
	 *
	 */
	private static final long serialVersionUID = 4180491670576658298L;

	private static final Logger logger = Logger.getLogger(EditarEquipamentoMBean.class);

	@Autowired
	private CLPService clpService;

	private CLP clp;

	private String idCLP;

	public void initialize() {
		logger.info("initialize...");
	}

	protected boolean verificaUsuarioLogado() {
		return true;
	}

	public void initializeAfter() {
		logger.info("initialize...");
		if (StringUtils.isNotBlank(idCLP)) {
			clp = clpService.buscarPorId(Long.parseLong(idCLP));
		} else {
			clp = new CLP();
		}
	}

	public void salvaCLP() {
		try {
			if (clp.getId() == null) {
				clpService.criar(clp);
			} else {
				clpService.atualizar(clp);
			}
		} catch (ValidationException e) {
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, e.getMessage(), null);
			FacesContext.getCurrentInstance().addMessage(null, message);
			return;
		}
		RequestContext.getCurrentInstance().closeDialog(null);
	}

	public void cancelaEdicaoCLP() {
		RequestContext.getCurrentInstance().closeDialog(null);
	}

	public CLP getClp() {
		return clp;
	}

	public void setClp(CLP clp) {
		this.clp = clp;
	}

	public String getIdCLP() {
		return idCLP;
	}

	public void setIdCLP(String idCLP) {
		this.idCLP = idCLP;
	}

	public Integer getFabricante() {
		if (clp.getFabricante() != null) {
			return clp.getFabricante().getCodigo();
		}
		return null;
	}

	public void setFabricante(Integer codigo) {
		if (codigo != null) {
			clp.setFabricante(Fabricante.getByCodigo(codigo));
		}
	}

	public List<SelectItem> getFabricantes() {
		List<SelectItem> fabricates = new ArrayList<SelectItem>();
		for (Fabricante f : Fabricante.values()) {
			fabricates.add(new SelectItem(f.getCodigo(), f.getDescricao()));
		}
		return fabricates;
	}

}
